package demo.mvc.views.login
{
	import demo.mvc.Notifications;
	import demo.mvc.models.AccountModel;
	import demo.mvc.views.main.MainView;
	
	import com.gamefx.mvc.Facade;
	import com.gamefx.mvc.View;
	import com.gamefx.mvc.classes.Notification;
	
	import flash.events.MouseEvent;
	
	import mx.controls.*;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	public class LoginView extends View
	{
		[Inject]
		public var accountModel:AccountModel;
		
		private var ui:LoginUI;

		
		public function LoginView(viewName:String=null, viewComponent:Object=null)
		{
			super(viewName, viewComponent);
		}
		
		override public function onRegister():void
		{
			super.onRegister();
						
			ui = new LoginUI();
			setViewComponent(ui);
			PopUpManager.addPopUp(ui, Test_Mvc.mainState);
			PopUpManager.centerPopUp(ui);
			
			handler(ui.btnLogin, MouseEvent.CLICK, btnLogin_clickHandler);
		}
		
		override public function onRemove():void
		{
			super.onRemove();
			
			PopUpManager.removePopUp(ui);
		}
		
		
		private function btnLogin_clickHandler(event:MouseEvent):void
		{
			if (ui.txtAccount.text.length == 0)
			{
				Alert.show("请输入帐号！", "", Alert.OK, null, function (event:CloseEvent):void{
					ui.txtAccount.setFocus();
				});
				return;
			}
			
			if (ui.txtPassword.text.length == 0)
			{
				Alert.show("请输入密码！", "", Alert.OK, null, function (event:CloseEvent):void{
					ui.txtPassword.setFocus();
				});
				return;
			}
			
			accountModel.login(ui.txtAccount.text, ui.txtPassword.text);
		}
		

		[Subscribe(name=Notifications.MSG_ACCOUNT_LOGIN)]
		
		public function loginResultHandler(notification:Notification):void
		{
			var result:int = notification.getBody() as int;
			
			if (result == 0)
			{
				facade.sendNotification(Notifications.CMD_SCENE_GOTO, Facade.Name(MainView));
			}
			else
			{
				Alert.show("用户名或密码错误，登录失败！\n\n(测试帐号：test  密码：1234)");
				ui.txtAccount.setFocus();
			}
		}
		
	}
}